<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div class="title">
          组织结构
        </div>
      </template>
      <div class="tree">
        <TreeItem :item="topInfo"></TreeItem>
      </div>
      <!-- 树形结构 -->
      <el-tree :data="list" :props="{ children: 'children' }">
        <template v-slot="{ data }">
          <TreeItem :item="data" style="width:100%"></TreeItem>
        </template>
      </el-tree>
    </el-card>
    <!-- 弹框组件 -->
    <Dialog :initDate="initDate"></Dialog>
  </div>
</template>

<script>
import TreeItem from '@/views/departments/components/tree-item1.vue'
import { companyDepartment } from '@/api/departments.js'
import Dialog from './components/dialog.vue'
export default {
  data () {
    return {
      list: [],
      initDate: [], // 存储原始架构数据
      topInfo: {
        name: '',
        manager: '负责人',
        isTop: true,
        id: '' // 子级的pid等于父级的id topInfo是最外层部门的父级
      }
    }
  },
  components: {
    TreeItem,
    Dialog
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      // 获取结构数据
      const res = await companyDepartment()
      // this.list = res.data.depts
      this.list = this.changeData(res.data.depts, '')
      this.topInfo.name = res.data.companyName
      console.log('架构信息', res)
      //  存储原始架构数据
      this.initDate = res.data.depts
    },
    changeData (arr, str = '') {
      // 将数据转换成树形结构
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 18px;
}
.el-card {
  padding: 40px;
  ::v-deep .el-card__header {
    padding: 10px 0;
    font-size: 14px;
  }
  ::v-deep .el-card__body {
    padding: 30px;
  }
  .tree {
    width: 100%;
    margin: 0 auto;
    font-size: 14px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 10px;
  }
}
.el-tree {
  margin-top: 20px;
  font-size: 14px;
}
::v-deep .el-tree-node {
  margin: 20px 0;
}
</style>
